package com.example.bbs.controller.util;

import com.example.bbs.entity.User;
import com.example.bbs.service.UserService;
import com.example.bbs.util.ConstUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * 本地图片储存
 * @author jiajiazi
 * @version 1.0
 * @date 2021/5/5 13:29
 */
@Controller
@RequestMapping("/upload")
public class UploadFile {

    @Autowired
    private UserService userService;

    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
    private final Random r = new Random();


    //md 上传图片  暂停使用
    @PostMapping("/mdjpg")
    public void uploadFileByEditormd(HttpServletRequest request,
                                     HttpServletResponse response,
                                     @RequestParam(name = "editormd-image-file", required = true)
                                             MultipartFile file) throws IOException {
        try {
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //生成文件名称通用方法
            StringBuilder tempName = new StringBuilder();
            tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
            String newFileName = tempName.toString();
            //创建文件
            //File destFile = new File(ConstUtil.FILE_UPLOAD_DISEASE + newFileName);
            //String fileUrl = ConstUtil.getHost(new URI(request.getRequestURL() + "")) + ConstUtil.IMG_DISEASE_TPATH + newFileName;
            //File fileDirectory = new File(ConstUtil.FILE_UPLOAD_DISEASE);
            //
            //if (!fileDirectory.exists()) {
            //    fileDirectory.mkdir();
            //}
            //file.transferTo(destFile);
            String path = QiNiuUtil.uploadQNImg((FileInputStream) file.getInputStream(), newFileName);

            request.setCharacterEncoding("utf-8");
            response.setHeader("Content-Type", "text/html");
            //response.getWriter().write("{\"success\": 1, \"message\":\"success\",\"url\":\"" + fileUrl + "\"}");
            response.getWriter().write("{\"success\": 1, \"message\":\"success\",\"url\":\"" + path + "\"}");
        } catch (UnsupportedEncodingException e) {
            response.getWriter().write("{\"success\":0}");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //上传article头像
    @RequestMapping("/artavator")
    @ResponseBody
    public String uploadArtAvator(HttpServletRequest request, HttpSession session, @RequestPart("art-imgfile") MultipartFile file) throws IOException {
        try {
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //生成文件名称通用方法
            StringBuilder tempName = new StringBuilder();
            tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
            String newFileName = tempName.toString();
            String fileurl = QiNiuUtil.uploadQNImg((FileInputStream) file.getInputStream(), newFileName);
            System.out.println("art: " + fileurl);
            return fileurl;
        } catch (IOException e) {
            e.printStackTrace();
            return "500";
        }
    }

    //上传头像
    @RequestMapping("/avatorimg")
    @ResponseBody
    public String uploadAvator(HttpServletRequest request, HttpSession session, @RequestPart("avatorfile") MultipartFile file) throws IOException {
        try {
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //生成文件名称通用方法
            StringBuilder tempName = new StringBuilder();
            tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
            String newFileName = tempName.toString();
            //创建文件
            //File destFile = new File(ConstUtil.FILE_UPLOAD_AVATOR + newFileName);
            //String fileUrl = ConstUtil.getHost(new URI(request.getRequestURL() + "")) + ConstUtil.IMG_DISEASE_TPATH + newFileName;
            //File fileDirectory = new File(ConstUtil.FILE_UPLOAD_AVATOR);
            //
            //if (!fileDirectory.exists()) {
            //    fileDirectory.mkdir();
            //}
            //file.transferTo(destFile);
            String path = QiNiuUtil.uploadQNImg((FileInputStream) file.getInputStream(), newFileName);
            System.out.println("user: " + path);
            User user = (User) session.getAttribute("user");
            if (user == null) {
                return "500";
            }
            //userService.updateUserAvator(user.getId(), ConstUtil.IMG_AVATOR_TPATH + newFileName);
            userService.updateUserAvator(user.getId(), path);
            return "200";
        } catch (IOException e) {
            e.printStackTrace();
            return "500";
        }
    }
}
